<?php
/**
 * Created by PhpStorm.
 * User: qiaoli
 * Date: 15/9/5
 * Time: 下午12:28
 */
define('IMBASEPATH', 'https://api.im.jpush.cn');
class Imapim extends CI_Model
{
    const TBL_NAME_GROUP_INFO = 'ry_group_info';
    const TBL_NAME_GROUP_MEMBER = 'ry_group_members';
    const TBL_NAME_GROUP_BOARD_HIS = 'ry_group_board_history';
    const TBL_NAME_GROUP_APPLY_FOR = 'ry_group_apply_for';
    const TBL_NAME_GROUP_RECOMMEND = 'ry_group_rec';

    const MEMBER_LEVEL_ADMIN = 9;
    const MEMBER_LEVEL_SUB_ADMIN = 1;
    const MEMBER_LEVEL_NORMAL = 0;

    const AUDIT_STATUS_SUBMIT = 1;
    const AUDIT_STATUS_REFUSE = 2;
    const AUDIT_STATUS_ACCEPT = 3;


    const NUM_GROUP_DETAIL    = 10;
    const NUM_GROUP_MEM_LIST  = 50;
    const NUM_GROUP_ALL       = 0;

    const NUM_ADMIN_LIMIT = 11;


    const MC_KEY_GROUP_INFO = "gs_group_info:";
    const MC_KEY_GROUP_ADMIN_INFO = "gs_group_admin_info:";
    const MC_KEY_GROUP_MEM_LST = "gs_group_mem_lst:";
    const MC_KEY_GROUP_ROLE_INFO = "gs_group_role_info:";
//    const MC_KEY_GROUP_IN_WHICH = "gs_group_in_which:";
    const MC_KEY_GROUP_RECOMMEND = "gs_group_recommend:";

    function __construct()
    {
        parent::__construct();
        $this->load->model("userm");
        $this->load->model("messagem");

        $this->load->library("rongyunim");
    }

    public function insert_user_db()
    {
        $info = array();
        $info['user_id'] = $this->uid;
        $info['addtime'] = time();
        $this->db->set($info);
        $result = $this->db->insert('ml_imuser');
        if ($result) {
            $return = $this->db->insert_id();
        } else {
            $return = false;
        }
        return $return;
    }

    public function regist($uid, $softversion)
    {
        // 更新融云log
        $this->load->model("rongyun_logm");
        $this->rongyun_logm->update_log($uid, $softversion);

        $request_params = array();
        $username = $this->im_username($uid);
        $request_params['username'] = $username;

        $userinfo = $this->userm->getUserInfoById($uid, 1);

        $password = md5($userinfo['password']);

        $url = IMBASEPATH . '/v1/users/';
        $post_data = array(array('username' => $username, 'password' => $password));
        $result = $this->imapim->curl_exec_im($url, $post_data);

        $info = explode('[{', $result);
        $re_str = '[{' . $info[1];
        $result_json = json_decode($re_str, true);
        $code = $result_json['error']['code'];
        return $code;
    }

    public function jg_list_admins()
    {
        $url = IMBASEPATH . '/v1/admins?start=0&count=20';

        $result = $this->curl_exec_im($url, array(), 'GET');
        return $result;
    }


    public function jg_list_groups($start = 0, $count = 20)
    {
        $url = IMBASEPATH . "/v1/groups?start={$start}&count={$count}";

        $result = $this->curl_exec_im($url, array(), 'GET');
        return $result;
    }


    public function jg_list_group_members($gid)
    {
        $url = IMBASEPATH . "/v1/groups/{$gid}/members/";

        $result = $this->curl_exec_im($url, array(), 'GET');
        return $result;
    }


    public function jg_list_group_info($gid)
    {
        $url = IMBASEPATH . "/v1/groups/{$gid}";

        $result = $this->curl_exec_im($url, array(), 'GET');
        return $result;
    }

    public function add_members($gid)
    {
        $url = IMBASEPATH . '/v1/groups/' . $gid . '/members';
        $list = array("qyyx_52886",
            "qyyx_217667",
            "qyyx_266284",
            "qyyx_248779",
            "qyyx_45943",
            "qyyx_31495",
            "qyyx_85039",
            "qyyx_93838",
            "qyyx_93840",
            "qyyx_93841",
            "qyyx_93843",
            "qyyx_104814",
            "qyyx_104816",
            "qyyx_104820",
            "qyyx_104876",
            "qyyx_109326",
            "qyyx_265853",
            "qyyx_213697",
            "qyyx_37846",
            "qyyx_93848",
            "qyyx_93850",
            "qyyx_93852",
            "qyyx_93853",
            "qyyx_93855",
            "qyyx_222758",
            "qyyx_46472",
            "qyyx_224276",
            "qyyx_242397",
            "qyyx_263038",
            "qyyx_24439",
            "qyyx_246482",
            "qyyx_93677",
            "qyyx_87307",
            "qyyx_12711",
            "qyyx_234729",
            "qyyx_245559",
            "qyyx_81101",
            "qyyx_266278",
            "qyyx_51667",
            "qyyx_178608",
            "qyyx_178617",
            "qyyx_178626",
            "qyyx_178631",
            "qyyx_178645",
            "qyyx_178649",
            "qyyx_178651",
            "qyyx_178661",
            "qyyx_178670",
            "qyyx_3032",
            "qyyx_70877",
            "qyyx_70883",
            "qyyx_80150",
            "qyyx_80175",
            "qyyx_91068",
            "qyyx_98493",
            "qyyx_106964",
            "qyyx_190367",
            "qyyx_220952",
            "qyyx_220963",
            "qyyx_221005",
            "qyyx_221017",
            "qyyx_237619",
            "qyyx_255035",
            "qyyx_232513",
            "qyyx_227907",
            "qyyx_137692",
            "qyyx_179492",
            "qyyx_228053",
            "qyyx_169287",
            "qyyx_112321",
            "qyyx_258746",
            "qyyx_248856",
            "qyyx_191000",
            "qyyx_248915",
            "qyyx_153838",
            "qyyx_48133",
            "qyyx_105305",
            "qyyx_262581",
            "qyyx_235183",
            "qyyx_258696",
            "qyyx_243463",
            "qyyx_227178",
            "qyyx_234041",
            "qyyx_127305",
            "qyyx_246599",
            "qyyx_248327",
            "qyyx_248328",
            "qyyx_248443",
            "qyyx_248862",
            "qyyx_253698",
            "qyyx_254146",
            "qyyx_255699",
            "qyyx_264674",
            "qyyx_266445",
            "qyyx_178773",
            "qyyx_178881",
            "qyyx_211337",
            "qyyx_223255",
            "qyyx_242299",
            "qyyx_245849",
            "qyyx_248533",
            "qyyx_249637",
            "qyyx_249674",
            "qyyx_249718",
            "qyyx_249850",
            "qyyx_265128",
            "qyyx_222975",
            "qyyx_222196",
            "qyyx_184338",
            "qyyx_217835",
            "qyyx_3",
            "qyyx_4",
            "qyyx_16159",
            "qyyx_32062",
            "qyyx_34986",
            "qyyx_47827",
            "qyyx_51821",
            "qyyx_52521",
            "qyyx_63568",
            "qyyx_66788",
            "qyyx_70875",
            "qyyx_70878",
            "qyyx_70920",
            "qyyx_78767",
            "qyyx_79132",
            "qyyx_80402",
            "qyyx_89821",
            "qyyx_89843",
            "qyyx_91059",
            "qyyx_93763",
            "qyyx_113111",
            "qyyx_113126",
            "qyyx_121230",
            "qyyx_126500",
            "qyyx_133371",
            "qyyx_141217",
            "qyyx_168752",
            "qyyx_176065",
            "qyyx_178589",
            "qyyx_178591",
            "qyyx_178597",
            "qyyx_178599",
            "qyyx_178605",
            "qyyx_178622",
            "qyyx_178657",
            "qyyx_178669",
            "qyyx_190365",
            "qyyx_221008",
            "qyyx_221024",
            "qyyx_243248",
            "qyyx_246333",
            "qyyx_246526",
            "qyyx_246700",
            "qyyx_247098",
            "qyyx_255260");
        $post_data = array("add" => $list);
        $result = $this->imapim->curl_exec_im($url, $post_data);
        //echo json_encode($result);
        $info = explode('[{', $result);
        $re_str = '[{' . $info[1];
        $result_json = json_decode($re_str, true);
        $code = $result_json['error']['code'];
        return $code;
    }

    public function reset_passwd($uid)
    {
        $userinfo = $this->userm->getUserInfoById($uid);
        $password = md5($userinfo['password']);
        $username = $this->im_username($uid);

        $post_data = array('new_password' => $password);

        $url = IMBASEPATH . '/v1/users/' . $username . '/password';

        $result = $this->curl_exec_im($url, $post_data, 'PUT');
        return $result;
    }

    public function exec_update_userinfo($uid)
    {
        $userinfo = $this->userm->getUserInfoById($uid, 1);
        $username = $this->im_username($uid);
        $nickname = $userinfo['username'];
        $avatar = $userinfo['head_ico'];
        $post_data = array('nickname' => $nickname);

        $url = IMBASEPATH . '/v1/users/' . $username;

        $result = $this->curl_exec_im($url, $post_data, 'PUT');
        return $result;
    }

    public function group_members($gid)
    {
        $url = IMBASEPATH . '/v1/groups/' . $gid . '/members/';
        $result = $this->curl_exec_im($url, array(), 'GET');
        $members = json_decode($result);

        $data = array();
        foreach ($members as $value) {
            $oneUser = (array)$value;
            $im_username = $oneUser['username'];
            $user_id = $this->un_im_username($im_username);
            $userinfo = $this->userm->get_one_user_4_search($user_id, $this->uid);
            $oneUser['userinfo'] = $userinfo;
            $data[] = $oneUser;
        }
        return $data;
    }


    public function jg_del_member($uid)
    {
        $username = $this->im_username($uid);
        $url = IMBASEPATH . "/v1/users/{$username}";

        $result = $this->curl_exec_im($url, null, 'DELETE');

        $default = <<<str
HTTP/1.1 204 No Content
Server: nginx
Date: Wed, 09 Mar 2016 07:21:57 GMT
Content-Type: application/json; charset=UTF-8
Connection: keep-alive

str;
        if (strpos($result, '204 No Content') === FALSE) {
            return FALSE;
        }
        return True;
    }

    function curl_exec_im($url, $post_data, $method = 'POST')
    {
        $a_str1 = $this->authorization_header();
        $header = array($a_str1, 'Content-Type: application/json');

        $ch = curl_init();
        if ($method == 'POST') {
            curl_setopt($ch, CURLOPT_POST, 1);
        } else if ($method == 'PUT') {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
        } else if ($method == 'DELETE') {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
        }

        if ($method != 'GET') {
            curl_setopt($ch, CURLOPT_HEADER, true);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        if ($post_data) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        $info = curl_getinfo($ch);
        $http_code = $info['http_code'];
        if ($http_code != 200 || $http_code != 201) {
            return $result;
        }
        curl_close($ch);
        return $result;
    }

    function im_username($uid)
    {
        $username = 'qyyx_' . $uid;
        return $username;
    }

    function un_im_username($im_username)
    {
        $user_id = str_replace("qyyx_", "", $im_username);
        return $user_id;
    }

    function authorization_header()
    {
        $app_key = 'f11580c3c78744c6ecb36900';
        $secret = '528a2bd21d3629a0d5012606';
        $auth_str = $app_key . ':' . $secret;

        $base64_str = base64_encode($auth_str);
        return 'Authorization: Basic ' . $base64_str;
    }




    /*
     * ==============================
     *
     *   融云 IM
     *
     * ==============================
     */


    /*
     * ############## 操作
     */

    /**
     * 注册
     * @param $uid
     * @return array {"code"=>200, "token"=>"", "error_tips"=>""}
     */
    public function registerRongYunIM($uid, $softversion)
    {
        // 更新融云log
        $this->load->model("rongyun_logm");
        $this->rongyun_logm->update_log($uid, $softversion);

        $userinfo = $this->userm->getUserInfoById($uid, 1);
        return $this->rongyunim->getToken($uid, $userinfo["username"], $userinfo["head_ico"]);
    }


    private function gs_trans_uinfo2mem($uinfo)
    {
        ci_load_once('threadm');
        return array(
            "mname" => $uinfo["username"],
            "mhead_ico" => $uinfo["head_ico"],
            "mis_expert" => $uinfo["user_level"] ? 1 : 0,
            "mverified_status" => $uinfo["verified_status"],
            "mpractice_hospital" => $uinfo["practice_hospital"],
            "mpost_title" => $uinfo["post_title"],
            "mthread" => is_numeric($uinfo["thread"]) ? $this->threadm->get_thread_name($uinfo["thread"]) : $uinfo["thread"],
            "madmin_level" => $uinfo["admin_level"],
        );
    }


    /**
     * 创建群
     */
    public function gs_create($uid, $gname, $gdesc = "")
    {
        if (!$uid) {
            return [-2, "群主id不能为空"];
        }
        if (empty($gname)) {
            return [-3, "群名称不能为空"];
        }

        $admin_info = $this->userm->getUserInfoById($uid);
        $data = array(
            "gauid" => $uid,
            "gausername" => $admin_info["username"],
            "gahead_ico" => $admin_info["head_ico"],
            "gname" => $gname,
            "gdesc" => $gdesc,
            "ctime" => time(),
        );

        $this->db->set($data);
        $result = $this->db->insert(self::TBL_NAME_GROUP_INFO);
        if (!$result) {
            return [-4, "群档案创建失败"];
        }

        $gid = $this->db->insert_id();

        # 设置群主
        $data = array(
            "gid" => $gid,
            "uid" => $uid,
            "mlv" => self::MEMBER_LEVEL_ADMIN,
            "atime" => time(),
        );
        $data = array_merge($this->gs_trans_uinfo2mem($admin_info), $data);

        $result = $this->db->insert(self::TBL_NAME_GROUP_MEMBER, $data);
        if (!$result) {
            return [-5, "群主设置失败"];
        }

        $result = $this->rongyunim->groupCreate($uid, $gid, $gname);
        if ((isset($result["code"]) && $result["code"] == "200")) {
            return [0, $gid];
        }

        $tips = isset($result["error_tips"]) ? $result["error_tips"] : "创建失败, error_code:" . $result["code"];
        return [-6, $tips];
    }


    /**
     * 新增群成员
     */
    public function gs_member_add($gid, $uid_arr_new)
    {
        $mem_arr_old = $this->gs_member_list($gid, null, 1, self::NUM_GROUP_ALL);
        $mem_dict = array();
        foreach ($mem_arr_old as $mem) {
            $mem_dict[$mem["uid"]] = 1;
        }
        unset($mem_arr_old);

        $mem_left = array();
        foreach ($uid_arr_new as $uid) {
            if (isset($mem_dict[$uid])) {
                continue;
            }
            $mem_left[] = $uid;
        }
        unset($mem_dict);

        if (empty($mem_left)) {
            return false;
        }

        $mem_lst_info = $this->userm->getUserInfoByIds($mem_left);
        unset($mem_left);
        $ginfo = $this->gs_group_info($gid);

        $mem_lst = array();
        foreach ($mem_lst_info as $minfo) {
            $res = $this->rongyunim->groupJoin($minfo["id"], $gid, $ginfo["gname"]);
            if ($res["code"] != '200') {
                continue;
            }

            $data = array(
                "gid" => $gid,
                "uid" => $minfo["id"],
                "atime" => time(),
            );
            $data = array_merge($this->gs_trans_uinfo2mem($minfo), $data);

            $mem_lst[$minfo["id"]] = $data;
        }
        unset($mem_lst_info);

        $num_add = $this->db->insert_batch(self::TBL_NAME_GROUP_MEMBER, $mem_lst);
        if ($num_add) {
            $key_prefix = self::MC_KEY_GROUP_MEM_LST . $gid . ':*';
            $keys = $this->redis->keys($key_prefix);
            
            if (! empty($keys)) {
                foreach ($keys as $v) {
                    $this->redis->delete($v);
                }
            }
        }

        unset($data);

        return $mem_lst;
    }


    /**
     * 更新群信息
     */
    public function gs_group_info_update($gid, $uid, $update)
    {
        if (empty($update)) {
            return array(1, '不用更新');
        }

        if (isset($update['gboard'])) {
            $board_data = array(
                "gid" => $gid,
                "gboard" => $update['gboard'],
                'adduser' => $uid,
                'addtime' => time(),
            );

            $this->db->insert(self::TBL_NAME_GROUP_BOARD_HIS, $board_data);
        }

        $this->db->where("gid", $gid);
        $result = $this->db->update(self::TBL_NAME_GROUP_INFO, $update);
        if ($result) {
            $key = self::MC_KEY_GROUP_INFO . $gid;
            $this->redis->delete($key);
        }
        return $result;
    }


    /**
     * 更新某群组成员信息
     */
    public function gs_member_info_update($gid, $uid, $data)
    {
        # keys: mid, gid, uid, mname, mlv, atime, mhead_ico, mute
        $whe = array("gid" => $gid, "uid" => $uid);
        $this->db->update(self::TBL_NAME_GROUP_MEMBER, $data, $whe);

        return $this->gs_mem_role_info($gid, $uid, 1);
    }


    /**
     * @param $gid
     * @param $uid: 当前用户
     * @param $id_remove: 被操作用户
     * @return array
     */
    public function gs_member_remove($gid, $uid, $id_remove)
    {
        $user_info = $this->gs_mem_role_info($gid, $uid);
        $mem_info = $this->gs_mem_role_info($gid, $id_remove);
        if (empty($user_info)) {
            return [1, '您已不在群里'];
        }
        elseif (empty($mem_info)) {
            return [1, '被处理用户已不在群里'];
        }
        elseif ($mem_info["mlv"] == Imapim::MEMBER_LEVEL_ADMIN) {
            return [1, '群主不能直接退群, 操作失败'];
        }
        elseif ($uid != $id_remove && ($mem_info['mlv'] > self::MEMBER_LEVEL_NORMAL && $user_info['mlv'] < self::MEMBER_LEVEL_ADMIN)) {
            return [2, '只有群主可以删出管理员'];
        }

        $result = $this->rongyunim->groupQuit($id_remove, $gid);
        if ((isset($result["code"]) && $result["code"] == "200")) {
            $this->db->delete(self::TBL_NAME_GROUP_MEMBER, array("uid" => $id_remove, "gid" => $gid));

            $key_prefix = self::MC_KEY_GROUP_MEM_LST . $gid . ':*';
            $keys = $this->redis->keys($key_prefix);

            $keys[] = self::MC_KEY_GROUP_ROLE_INFO . "{$gid}:{$id_remove}";

            if (! empty($keys)) {
                foreach ($keys as $v) {
                    $this->redis->delete($v);
                }
            }
            $this->db->set("is_expired", 1);
            $this->db->where(array("gid" => $gid, "from" => $id_remove));
            $this->db->update(self::TBL_NAME_GROUP_APPLY_FOR);
            return [0, "处理成功"];
        }
        $tips = isset($result["error_tips"]) ? $result["error_tips"] : "操作失败, error_code:" . $result["code"];
        return [1, $tips];
    }


    /**
     * 解散群
     */
    public function gs_member_dismiss($gid, $uid)
    {
        $mem_info = $this->gs_mem_role_info($gid, $uid);
        if (empty($mem_info)) {
            return [1, '获取用户群关系失败'];
        } elseif ($mem_info["mlv"] != Imapim::MEMBER_LEVEL_ADMIN) {
            return [1, '权限不足, 只有才能群主解散群'];
        }
        $result = $this->rongyunim->groupDismiss($uid, $gid);
        if ((isset($result["code"]) && $result["code"] == "200")) {
            $this->db->delete(self::TBL_NAME_GROUP_MEMBER, array("gid" => $gid));

            $key_prefix = self::MC_KEY_GROUP_MEM_LST . $gid . ':*';
            $keys = $this->redis->keys($key_prefix);

            $key_prefix = self::MC_KEY_GROUP_ROLE_INFO . $gid . ':*';
            $keys_tmp = $this->redis->keys($key_prefix);
            $keys = array_merge($keys, $keys_tmp);

            $keys[] = self::MC_KEY_GROUP_INFO . $gid;
            $keys[] = self::MC_KEY_GROUP_ADMIN_INFO . $gid;
            $keys[] = self::MC_KEY_GROUP_RECOMMEND;

            if (! empty($keys)) {
                foreach ($keys as $v) {
                    $this->redis->delete($v);
                }
            }

            return [0, $gid];
        }
        $tips = isset($result["error_tips"]) ? $result["error_tips"] : "操作失败, error_code:" . $result["code"];
        return [1, $tips];
    }


    /**
     * 新用户请求入群
     * @param $ginfo
     * @param $user_info
     * @param $role_info
     * @return array
     */
    public function gs_add_audit_submit($ginfo, $user_info, $role_info,$invite =0)
    {
        $apply_status = self::AUDIT_STATUS_SUBMIT;

        if (!empty($role_info)) {
            return [0, "您已经在群里了"];
        }

        $whe = array("gid" => $ginfo["gid"], "from" => $user_info["id"], "is_expired" => "0");
        $this->db->select()->where($whe);
        $this->db->order_by("aid", "desc");
        $query_old = $this->db->get(self::TBL_NAME_GROUP_APPLY_FOR);
        if ($query_old && $query_old->row_array()) {
            $apply_old = $query_old->row_array();

            if ($apply_old["apply_status"] == self::AUDIT_STATUS_SUBMIT) {
                // 用户已提交的请求正在等待审核
                return [0, "已经提交审核"];
            } elseif ($apply_old["apply_status"] == self::AUDIT_STATUS_ACCEPT) {
                // 用户已提交的请求通过审核
                return [0, "请求已经通过审核"];
            }
        }
        if($invite)
        {
            $msg_chat = $this->messagem->build_group_chat_msg(
                $ginfo["gicon"], $ginfo["gname"],
                "{$invite['username']}邀请{$user_info["username"]}加入群聊，请审核", $ginfo["gid"],
                $user_info["id"], $apply_status
            );

            //普通成员邀请用户,给邀请用户发通知
            $msg_invite = $this->messagem->build_group_chat_msg(
                $ginfo["gicon"], $ginfo["gname"],
                "{$invite['username']}邀请您加入群聊，正在审核", $ginfo["gid"],
                $ginfo["gauid"], $apply_status
            );

            $this->messagem->send_chat_msg(
                $ginfo["gauid"], $user_info["id"], $msg_invite, Messagem::CHAT_NOTICE_GROUP
            );

        }else{
            $msg_chat = $this->messagem->build_group_chat_msg(
                $user_info["head_ico"], $user_info["username"],
                "申请加入该群聊《{$ginfo["gname"]}》", $ginfo["gid"],
                $user_info["id"], $apply_status
            );
        }


        $admin_ids = $this->get_admin_ids($ginfo["gid"]);
        // 发给群主『待审核』消息, msgtype 应该是 审核类型, messagem::CHAT_NOTICE_AUDIT
        $this->messagem->send_chat_msg(
            $user_info["id"], $admin_ids, $msg_chat, Messagem::CHAT_NOTICE_AUDIT
        );

        // 提交待审核请求
        $data = array(
            "gid" => $ginfo["gid"],
            "apply_status" => $apply_status,
            "from" => $user_info["id"],
            "actime" => time(),
        );

        $result = $this->db->insert(self::TBL_NAME_GROUP_APPLY_FOR, $data);

        return [0, "已经提交审核"];
    }


    public function gs_add_audit_refuse($ginfo, $user_info, $role_info, $msg_id,$uid=0)
    {
        $apply_status = self::AUDIT_STATUS_REFUSE;

        if ($role_info) {
            return [0, "数据已过期, 请刷新  1x0"];
        }

        $whe = array("gid" => $ginfo["gid"], "from" => $user_info["id"], "is_expired" => "0");
        $this->db->select()->where($whe);
        $this->db->order_by("aid", "desc");
        $query_old = $this->db->get(self::TBL_NAME_GROUP_APPLY_FOR);
        if ($query_old && $query_old->row_array()) {
            $apply_old = $query_old->row_array();

            $tips = "";
            if ($apply_old["apply_status"] == self::AUDIT_STATUS_SUBMIT) {
                // 正常情况, 不处理
            } elseif ($apply_old["apply_status"] == self::AUDIT_STATUS_REFUSE) {
                // 此时无待审核消息
                $tips = "审核已发送 1x0";
            } elseif ($apply_old["apply_status"] == self::AUDIT_STATUS_ACCEPT) {
                // 此时无待审核消息
                $tips = "审核已发送 1x1";
            }

            if ($tips) {
                return [0, $tips];
            }
        } else {
            return [1, "数据已过期, 请刷新 1x1"];
        }

        $msg_chat = $this->messagem->build_group_chat_msg(
            $ginfo["gicon"], $ginfo["gname"],
            "申请加入该群聊已被拒绝，加入失败", $ginfo["gid"],
            $ginfo["gauid"], $apply_status
        );

        // 发给用户群申请结果, msgtype 应该是 群通知类型, messagem::CHAT_NOTICE_GROUP
        $this->messagem->send_chat_msg(
            $ginfo["gauid"], $user_info["id"], $msg_chat, Messagem::CHAT_NOTICE_GROUP
        );

        // 更新请求表中数据
        $updata = array("apply_status" => $apply_status,'admin_id'=>$uid);
        $this->db->set($updata);
        $this->db->where(array("aid" => $apply_old["aid"]));
        $this->db->limit(1);
        $this->db->update(self::TBL_NAME_GROUP_APPLY_FOR);

        if ($msg_id) {
            // 更新群主『待审核』消息, 为『已拒绝』
            $msg_chat = $this->messagem->build_group_chat_msg(
                $user_info["head_ico"], $user_info["username"],
                "申请加入该群聊《{$ginfo["gname"]}》", $ginfo["gid"],
                $user_info["id"], $apply_status
            );
            $this->messagem->update_msg_content($msg_id, $msg_chat);
        }

        return [0, "审核发送成功"];
    }


    public function gs_add_audit_accept($ginfo, $user_info, $role_info, $msg_id,$uid=0)
    {
        $apply_status = self::AUDIT_STATUS_ACCEPT;

        if ($role_info) {
            return [0, "请求已被通过"];
        }

        $whe = array("gid" => $ginfo["gid"], "from" => $user_info["id"], "is_expired" => "0");
        $this->db->select()->where($whe);
        $this->db->order_by("aid", "desc");
        $query_old = $this->db->get(self::TBL_NAME_GROUP_APPLY_FOR);
        if ($query_old && $query_old->row_array()) {
            $apply_old = $query_old->row_array();

            $tips = "";
            if ($apply_old["apply_status"] == self::AUDIT_STATUS_SUBMIT) {
                // 正常情况, 不处理
            } elseif ($apply_old["apply_status"] == self::AUDIT_STATUS_REFUSE) {
                // 此时无待审核消息
                $tips = "审核已发送 2x0";
            } elseif ($apply_old["apply_status"] == self::AUDIT_STATUS_ACCEPT) {
                // 此时无待审核消息
                $tips = "审核已发送 2x1";
            }

            if ($tips) {
                return [0, $tips];
            }
        } else {
            return [1, "数据已过期, 请刷新 2x1"];
        }

        $msg_chat = $this->messagem->build_group_chat_msg(
            $ginfo["gicon"], $ginfo["gname"],
            "申请加入该群聊已被通过，成功加入", $ginfo["gid"],
            $ginfo["gauid"], $apply_status
        );
        // 发给用户群申请结果, msgtype 应该是 群通知类型 messagem::CHAT_NOTICE_GROUP
        $this->messagem->send_chat_msg(
            $ginfo["gauid"], $user_info["id"], $msg_chat, Messagem::CHAT_NOTICE_GROUP
        );

        // 更新请求表中数据
        $updata = array("apply_status" => $apply_status,'admin_id'=>$uid);
        $this->db->set($updata);
        $this->db->where(array("aid" => $apply_old["aid"]));
        $this->db->limit(1);
        $this->db->update(self::TBL_NAME_GROUP_APPLY_FOR);

        // 更新群主『待审核』消息, 为『已批准』
        if ($msg_id) {
            // 更新群主『待审核』消息, 为『已拒绝』
            $msg_chat = $this->messagem->build_group_chat_msg(
                $user_info["head_ico"], $user_info["username"],
                "申请加入该群聊《{$ginfo["gname"]}》", $ginfo["gid"],
                $user_info["id"], $apply_status
            );
            $this->messagem->update_msg_content($msg_id, $msg_chat);
        }

        // 拉人入群
        $this->gs_member_add($ginfo["gid"], array($user_info["id"]));

        return [0, "审核发送成功"];
    }


    /**
     * 设置群成员等级
     *
     * @param $ginfo
     * @param $user_info
     * @param $role_info
     * @param $set_level
     * @return array
     */
    public function gs_set_level($ginfo, $user_info, $role_info, $set_level)
    {
        $gid = $ginfo['gid'];
        $uid = $user_info['id'];
        if ($ginfo["gauid"] == $uid || $set_level == self::MEMBER_LEVEL_ADMIN) {
            return [1, "权限不足"];
        }
        if (! in_array($set_level, [self::MEMBER_LEVEL_NORMAL, self::MEMBER_LEVEL_SUB_ADMIN])) {
            return [2, "权限参数有误"];
        }
        if ($role_info["mlv"] == $set_level) {
            return [0, "操作完成, 无权限变化"];
        }

        if ($role_info["mlv"] == self::MEMBER_LEVEL_NORMAL && $set_level > self::MEMBER_LEVEL_NORMAL) {
            $num_admin = $this->db->where(['mlv>'=>self::MEMBER_LEVEL_NORMAL, 'gid'=>$gid])->count_all_results(self::TBL_NAME_GROUP_MEMBER);
            if ($num_admin >= self::NUM_ADMIN_LIMIT) {
                return [1, "群主数量已达上限"];
            }
        }

        $updata = array("mlv" => $set_level);
        $this->db->set($updata);
        $this->db->where(array("mid" => $role_info["mid"]));
        $this->db->update(self::TBL_NAME_GROUP_MEMBER);


        $key_prefix = self::MC_KEY_GROUP_MEM_LST . $gid . ':*';
        $keys = $this->redis->keys($key_prefix);

        $keys[] = self::MC_KEY_GROUP_ROLE_INFO . "{$gid}:{$uid}";

        if (! empty($keys)) {
            foreach ($keys as $v) {
                $this->redis->delete($v);
            }
        }

        return [0, "设置成功"];
    }


    /**
     * 发送群通知
     * @param int $gid
     * @param string $one_word
     * @return array
     */
    public function gs_send_group_notice($gid, $one_word)
    {
//        $object_name = "RC:TxtMsg";
        $uid = "-1";    // 发送者需要是不在群里的用户
        $object_name = "RC:InfoNtf";
        $cont = json_encode(array("message" => $one_word));
        $result = $this->rongyunim->messageGroupPublish($uid, $gid, $object_name, $cont);
        if ((isset($result["code"]) && $result["code"] == "200")) {
            return [0, $result];
        }

        $tips = isset($result["error_tips"]) ? $result["error_tips"] : "发送群消息失败, error_code:" . $result["code"];
        return [1, $tips];
    }


    /**
     * 发送群聊天
     * @param int $gid
     * @param string $one_word
     * @param int $uid
     * @return array
     */
    public function gs_send_group_chat($gid, $one_word, $uid)
    {
        $object_name = "RC:TxtMsg";
        $cont = json_encode(array("content" => $one_word));
        $result = $this->rongyunim->messageGroupPublish($uid, $gid, $object_name, $cont);
        if ((isset($result["code"]) && $result["code"] == "200")) {
            return [0, $result];
        }

        $tips = isset($result["error_tips"]) ? $result["error_tips"] : "发送群消息失败, error_code:" . $result["code"];
        return [1, $tips];
    }



    /*
     * ############## 查询
     */


    /**
     * 查询讨论组成员信息
     * @param $discuss_uid_arr
     * @return array
     */
    public function discussionUserQueryRongYongIM($discuss_uid_arr)
    {
        $data = array();

        foreach ($discuss_uid_arr as $uid) {
            if (!$uid) {
                continue;
            }

            $userinfo = $this->userm->get_one_user_4_search($uid, $this->uid);
            $oneUser['userinfo'] = $userinfo;

            $oneUser["username"] = $userinfo["username"];
            $oneUser["user_id"] = $userinfo["id"];

            $data[] = $oneUser;
        }

        return $data;
    }


    /**
     * 查询群成员列表
     * @param $gid
     * @param $lv_limit
     * @param $page
     * @param $page_size
     * @return mixed
     */
    public function gs_member_list($gid, $lv_limit = null, $page = 1, $page_size = self::NUM_GROUP_MEM_LIST)
    {
        $tmp_key = ' ';
        if (! isset($lv_limit)) {
            // pass
        }
        elseif ($lv_limit == 0) {
            $tmp_key = '0';
            $this->db->where('mlv', self::MEMBER_LEVEL_NORMAL);
        }
        elseif ($lv_limit == 1) {
            $tmp_key = '1';
            $this->db->where('mlv>', self::MEMBER_LEVEL_NORMAL);
            $this->db->where('mlv<', self::MEMBER_LEVEL_ADMIN);
        }
        $key = self::MC_KEY_GROUP_MEM_LST . "{$gid}:{$tmp_key}:{$page}:{$page_size}";
        $old_data = $this->redis->getCache($key);
        if (!empty($old_data)) {
            return $old_data;
        }

        $this->db->select("*");

        $whe = array("gid" => $gid);
        $this->db->where($whe);

        $this->db->from(self::TBL_NAME_GROUP_MEMBER);

        $this->db->order_by("mlv", "desc");
        $this->db->order_by("mname", "asc");

        if ($page_size) {
            if (!$page) {
                $page = 1;
            }
            $start = ($page - 1) * $page_size;
            $this->db->limit($page_size, $start);
        }

        $new_data = $this->db->get()->result_array();

        foreach($new_data as $k=>$v) {
            $v["thread_name"] = $v["mthread"];
            $new_data[$k] = $v;
        }

        $this->redis->saveCache($key, $new_data, 600);
        return $new_data;
    }



    /**
     * 查询群成员列表
     * @param $gid
     * @param $uid
     * @param $observer_id
     * @return mixed
     */
    public function gs_group_friend_list($gid, $uid, $observer_id) {
        $this->load->model('followm');
        $id_friend_lst = $this->followm->get_mutual_ids($uid);

        $data = array();
        if ($id_friend_lst) {
            $this->db->select("uid");
            $this->db->where(array("gid" => $gid));
            $this->db->where_in("uid", $id_friend_lst);
            $query = $this->db->get(self::TBL_NAME_GROUP_MEMBER);
            if ($query) {
                $data = $query->result_array();
            }
        }

        $arr = array();
        foreach ($data as $value) {
            $arr[$value["uid"]] = $value["uid"];
        }

        if (! isset($this->userm)) {
            $this->load->model('userm');
        }
        $friend_list = $this->userm->getUserInfoByIds($id_friend_lst);

        foreach ($friend_list as $k => $v) {
            $user_info = $this->userm->transFellowInfo($v, $observer_id);
            if (isset($arr[$v["id"]])) {
                $user_info["in_group"] = 1;
            } else {
                $user_info["in_group"] = 0;
            }
            $friend_list[$k] = $user_info;
        }

        $usernames = array_column($friend_list, "username");
        array_multisort($usernames, SORT_ASC, $friend_list);

        return array_values($friend_list);
    }


    /**
     * 查询群成员列表, specified for 群简介
     */
    public function gs_member_list_for_detail($gid)
    {
        return $this->gs_member_list($gid, null, 1, self::NUM_GROUP_DETAIL);
    }


    /**
     * 查询群成员数量
     * @param $gid
     * @return int|mixed
     */
    public function gs_member_num($gid)
    {
        $result = $this->db->select()->where("gid", $gid)->count_all_results(self::TBL_NAME_GROUP_MEMBER);

        if (! isset($result)) {
            $result = 1;
        }

        return $result;
    }


    public function gs_admin_info($gid)
    {
        if (!$gid) {
            return null;
        }
        $key = self::MC_KEY_GROUP_ADMIN_INFO . $gid;
        $old_data = $this->redis->getCache($key);
        if (!empty($old_data)) {
            return $old_data;
        }

        $whe = array("gid" => $gid, 'mlv' => self::MEMBER_LEVEL_ADMIN);
        $query = $this->db->select()->where($whe)->get(self::TBL_NAME_GROUP_MEMBER);
        $new_data = array();
        if ($query) {
            $new_data = $query->row_array();
            $this->redis->saveCache($key, $new_data, 600);
        }

        return $new_data;
    }


    /**
     * 查询基本群信息
     * @param $gid
     * @return mixed|null
     */
    public function gs_group_info($gid)
    {
        if (!$gid) {
            return null;
        }

        $key = self::MC_KEY_GROUP_INFO . $gid;
        $old_data = $this->redis->getCache($key);
        if (!empty($old_data)) {
            return $old_data;
        }

        $whe = array("gid" => $gid, 'gprop !=' => 0);
        $query = $this->db->select()->where($whe)->get(self::TBL_NAME_GROUP_INFO);
        $new_data = array();
        if ($query) {
            $new_data = $query->row_array();

            if (isset($new_data['gicon'])) {
                $new_data['gicon'] = ret_fullpath_url($new_data['gicon']);
            }
            if (isset($new_data['gahead_ico'])) {
                $new_data['gahead_ico'] = ret_fullpath_url($new_data['gahead_ico']);
            }
            $this->redis->saveCache($key, $new_data, 600);
        }

        return $new_data;
    }


    /**
     * 查询某用户是否已加入某群
     * @param $gid
     * @param $uid
     * @param $nocache
     * @return array|null
     */
    public function gs_mem_role_info($gid, $uid, $nocache = 0)
    {
        if (!$gid || !$uid) {
            return null;
        }

        $key = self::MC_KEY_GROUP_ROLE_INFO . "{$gid}:{$uid}";
        $old_data = $this->redis->getCache($key);
        if (!empty($old_data) && !$nocache) {
            return $old_data;
        }

        $whe = array("gid" => $gid, 'uid' => $uid);
        $query = $this->db->select()->where($whe)->get(self::TBL_NAME_GROUP_MEMBER);
        $new_data = array();
        if ($query) {
            $new_data = $query->row_array();
            $this->redis->saveCache($key, $new_data, 600);
        }


        return $new_data;
    }


    /**
     * 查询某用户是已加入哪些群
     * @param $uid
     * @return array|null
     */
    public function gs_mem_in_which($uid, $order = [], $page = 1, $page_size = 0)
    {
        if (!$uid) {
            return null;
        }

        $this->db->select(self::TBL_NAME_GROUP_INFO . '.*, ' . self::TBL_NAME_GROUP_MEMBER . '.mute');
        $this->db->from(self::TBL_NAME_GROUP_INFO);
        $this->db->join(
            self::TBL_NAME_GROUP_MEMBER,
            self::TBL_NAME_GROUP_INFO . ".gid=" . self::TBL_NAME_GROUP_MEMBER . ".gid",
            "left"
        );
        $whe = array('gprop !=' => 0, "uid" => $uid);
        $this->db->where($whe);
        foreach ($order as $k => $v) {
            $this->db->order_by($k, $v);
        }
        if ($page_size) {
            if ($page < 1) {
                $page = 1;
            }
            $this->db->limit($page_size, ($page - 1) * $page_size);
        }
        $query = $this->db->get();
        $new_data = array();
        if ($query) {
            $result = $query->result_array();
            foreach ($result as $itm) {
                $new_data[$itm["gid"]] = $itm;
            }
        }

        return $new_data;
    }


    /**
     * 群推荐列表获取
     * @return array|mixed
     */
    public function gs_group_recommend_list()
    {
        $key = self::MC_KEY_GROUP_RECOMMEND;
        $old_data = $this->redis->getCache($key);
        if (!empty($old_data)) {
            return $old_data;
        }

        $this->db->select(self::TBL_NAME_GROUP_INFO . '.*');
        $this->db->from(Imapim::TBL_NAME_GROUP_INFO);
        $this->db->join(
            self::TBL_NAME_GROUP_RECOMMEND,
            self::TBL_NAME_GROUP_INFO . ".gid=" . self::TBL_NAME_GROUP_RECOMMEND . ".gid",
            "left"
        );
        $this->db->where(array('status' => 1, 'gprop !=' => 0));
        $this->db->order_by("sort", "asc");
        $query = $this->db->get();

        $new_data = array();
        if ($query) {
            $new_data = $query->result_array();
            $this->redis->saveCache($key, $new_data, 12 * 60 * 60);
        }

        return $new_data;
    }

    /**
     * 极光签名算法
     * @return string
     */
    private function get_base64_auth_string()
    {
        return base64_encode('f11580c3c78744c6ecb36900:528a2bd21d3629a0d5012606');
    }

    /**
     * 极光 服务端调用IM 接口 header
     * @return array
     */
    private function get_jg_header()
    {
        $base64_auth_string = self::get_base64_auth_string();
        return array(
            'Content-type:application/json;charset=UTF-8',
            'Authorization:Basic ' . $base64_auth_string
        );
    }

    /**
     * 注册极光管理员帐号
     * @param $uid
     */
    public function register_admin($uid, $password = '')
    {
        $username = $this->im_username($uid);
        $url = 'https://api.im.jpush.cn/v1/admins/';

        $header = self::get_jg_header();
        $data = array(
            'username' => $username,
            'password' => $password
        );

        $data = json_encode($data);
        $result = curl($url, $data, 0, 0, $header);
        $result_arr = json_decode($result, true);
        if (isset($result_arr['error']) && $result_arr['error']) {
            w_log($result);
        }
        return $result;
    }

    /**
     * 极光IM 发送消息
     * @param $target_uid 目标用户ID
     * @param $message    消息内容
     * @param string $from_uid 管理员ID
     */
    public function jg_im_send_message($target_uid, $message, $from_uid = '31495')
    {
        $url = 'https://api.im.jpush.cn/v1/messages';
        $header = self::get_jg_header();

        $from_user_info = $this->userm->getUserInfo($from_uid);
        if ($from_user_info) {
            $from_name = $from_user_info['username'];
        } else {
            $from_name = '轻盈医学官方帐号';
        }

        $target_uid = self::im_username($target_uid);
        $from_uid = self::im_username($from_uid);

        $data = array(
            'version' => 1,
            'target_type' => "single",
            'target_id' => $target_uid,
            'from_type' => "admin",
            'from_id' => $from_uid,
            'from_name' => $from_name,
            'msg_type' => "text",
            'msg_body' => array(
                'extras' => array('key' => ''),
                'text' => $message,
            )
        );
        $data = json_encode($data);
        $result = curl($url, $data, 0, 0, $header);
        $result_arr = json_decode($result, true);
        if (isset($result_arr['error']) && $result_arr['error']) {
            w_log($result);
        }
        return $result;
    }

    /**
     * 极光，更新用户信息
     * @param $uid
     */
    public function jg_update_user_info($uid, $data)
    {
        $username = self::im_username($uid);
        $url = 'https://api.im.jpush.cn/v1/users/' . $username;
        $header = self::get_jg_header();

        $data = json_encode($data);

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $response = curl_exec($ch);
        return $response;
    }


    /**
     * RY-IM 给用户发私信
     * @param int $from_uid
     * @param string $one_word
     * @param $to
     * @return array
     */
    public function gs_send_normal_chat($from_uid, $one_word, $to, $custom_type = 0, $msg_source = 0)
    {
        if (!empty($custom_type)) $h5_custom_type = substr($custom_type, 0, 1);
        if (empty($custom_type)) {
            // 文本
            $object_name = "RC:TxtMsg";
            $cont = json_encode(array("content" => $one_word));
        } else if ($custom_type == 1 || $custom_type == 2) {
            // 病例，专题
            $object_name = "RCD:QYImPostCustomMessaage";
            $extra = $this->get_custom_post_info($one_word, $custom_type, $msg_source, $h5_custom_type);
            if (empty($extra)) return false;
            $cont = json_encode(array("content" => $extra['post_content'], "extra" => $extra));
        } else if (substr($custom_type, 0, 1) == 6 || $custom_type == 7) {
            // H5，图谱
            $object_name = "RCD:QYImCommonMessaage";
            $extra = $this->get_custom_post_info($one_word, $custom_type, $msg_source, $h5_custom_type);
            if (empty($extra)) return false;
            $cont = json_encode(array("content" => $extra['messageContent'], "extra" => $extra));
        } else if ($custom_type == 3 || $custom_type == 5) {
            // 问答，投票
            $object_name = "RCD:QYImAnswerAndVoteCustomMessaage";
            $extra = $this->get_custom_post_info($one_word, $custom_type, $msg_source, $h5_custom_type);
            if (empty($extra)) return false;
            $cont = json_encode(array("content" => $extra['post_content'], "extra" => $extra));
        } else if ($custom_type == 4) {
            // 个人中心
            $object_name = "RCD:QYImProfileCustomMessaage";
            $extra = $this->get_custom_post_info($one_word, $custom_type, $msg_source, $h5_custom_type);
            if (empty($extra)) return false;
            $cont = json_encode(array("content" => $extra['user_desc'], "extra" => $extra));
        }

        $result = $this->rongyunim->messagePublish($from_uid, $to, $object_name, $cont);

        if ((isset($result["code"]) && $result["code"] == "200")) {
            return [0, $result];
        }

        $tips = isset($result["error_tips"]) ? $result["error_tips"] : "发送聊天消息失败, error_code:" . $result["code"];
        return [1, $tips];
    }

    /* 获取目标贴信息源 (1:病例,2:专题,6:H5,7:图谱)*/
    public function get_custom_post_info($msg, $custom_type = 0, $msg_source = 0, $h5_custom_type = 1)
    {
        switch ($h5_custom_type) {
            case 1:
                # 病例详情
                $return = $this->share_release($custom_type, $msg);
                return $return;
                break;

            case 2:
                # 专题详情
                $return = $this->share_subject($custom_type, $msg);
                return $return;
                break;

            case 3:
                # 问答
                $return = $this->share_question($custom_type, $msg);
                return $return;
                break;

            case 4:
                # 个人中心
                $return = $this->share_center($custom_type, $msg);
                return $return;
                break;

            case 5:
                # 投票
                $return = $this->share_vote($custom_type, $msg);
                return $return;
                break;

            case 6:
                # H5详情
                $return = $this->share_h5($custom_type, $msg, $msg_source);
                return $return;
                break;

            case 7:
                # 图谱详情
                $return = $this->share_image($custom_type, $msg, $msg_source);
                return $return;
                break;

            default:
                # 其他
                break;
        }
    }

    /* 病例 */
    public function share_release($custom_type, $msg)
    {
        $custom_post = array();
        $this->load->model('postm');
        $this->load->model('attachmentsm');
        $img_info = $this->attachmentsm->get_post_img_info((string)$msg);
        $custom_post['post_first_image'] = $img_info['img_list'][0];
        $post_info = $this->postm->get_post_content((int)$msg, $cache = 1);
        if (empty($post_info)) return false;
        $custom_post['post_content'] = $post_info['message'];
        $custom_post['custom_type'] = (string)$custom_type;
        $custom_post['post_id'] = (string)$msg;
        if ($post_info['post_type'] == 1) {
            $custom_post['custom_isexpert'] = '1';
        } else {
            $custom_post['custom_isexpert'] = '0';
        }
        return $custom_post;
    }

    /* 问答 */
    public function share_question($custom_type, $msg)
    {
        $custom_post = array();
        $this->load->model('postm');
        $custom_post['post_first_image'] = '';
        $post_info = $this->postm->get_post_content((int)$msg, $cache = 1);
        if (empty($post_info)) return false;
        $custom_post['post_content'] = $post_info['message'] ? $post_info['message'] : $post_info['subject'];
        $custom_post['custom_type'] = (string)$custom_type;
        $custom_post['post_id'] = (string)$msg;
        $custom_post['custom_isexpert'] = '0';
        return $custom_post;
    }


    /* 个人中心 */
    public function share_center($custom_type, $msg)
    {
        $custom_user = array();
        $this->load->model('userm');
        $user_info = $this->userm->getUserInfoById((int)$msg);
        if (empty($user_info)) return false;
        $custom_user['user_id'] = (string)$msg;
        $custom_user['user_desc'] = $user_info['truename'] . ':' . $user_info['practice_hospital'] . $user_info['post_title'];
        $custom_user['head_icon'] = $user_info['head_ico'];
        $custom_user['custom_type'] = (string)$custom_type;
        return $custom_user;
    }


    /* 投票 */
    public function share_vote($custom_type, $msg)
    {
        $custom_post = array();
        $this->load->model('postm');
        $custom_post['post_first_image'] = '';
        $post_info = $this->postm->get_post_content((int)$msg, $cache = 1);
        if (empty($post_info)) return false;
        $custom_post['post_content'] = $post_info['message'] ? $post_info['message'] : $post_info['subject'];
        $custom_post['custom_type'] = (string)$custom_type;
        $custom_post['post_id'] = (string)$msg;
        $custom_post['custom_isexpert'] = '0';
        return $custom_post;
    }

    /* 专题 */
    public function share_subject($custom_type, $msg)
    {
        $subject_info = $this->db->from("ml_disubject")->where(array("is_show" => 1, "id" => (int)$msg))->get()->result_array();
        if (empty($subject_info)) return false;
        $custom_post['post_first_image'] = ret_fullpath_url($subject_info[0]['images_thumb']);
        $custom_post['post_content'] = $subject_info[0]['title'];
        $custom_post['custom_type'] = (string)$custom_type;
        $custom_post['post_id'] = (string)$msg;
        $custom_post['custom_isexpert'] = '0';
        return $custom_post;
    }

    /* 图谱 */
    public function share_image($custom_type, $msg, $msg_source)
    {
        $custom_post = array();
        $this->load->model('packagem');
        $img_info = $this->packagem->get_package_staic_content((int)$msg);
        if (empty($img_info)) return false;
        $custom_post['messageType'] = (string)$custom_type;
        $custom_post['msgContentId'] = (string)$msg;
        $custom_post['imageUrl'] = ret_fullpath_url($img_info['atlas_icon']);
        $custom_post['messageContent'] = $img_info['share_desc'];
        $custom_post['source'] = $msg_source;
        $custom_post['forwardUrl'] = $img_info['share_url'];
        return $custom_post;
    }

    /**
     * H5 类型说明
     * 61 帖子
     * 62 专题
     * 63 图谱
     * 64 邀请注册
     * 65 推广card
     * 66 系统消息
     */
    public function share_h5($custom_type, $msg, $msg_source)
    {
        switch ($custom_type) {
            case 61:
                # 帖子
                $return = $this->h5_share_release($custom_type, $msg, $msg_source);
                return $return;
                break;

            case 62:
                # 专题
                $return = $this->h5_share_subject($custom_type, $msg, $msg_source);
                return $return;
                break;

            case 63:
                # 图谱
                $return = $this->h5_share_img($custom_type, $msg, $msg_source);
                return $return;
                break;

            case 64:
                # 邀请注册
                $return = $this->h5_share_invite($custom_type, $msg, $msg_source);
                return $return;
                break;

            case 65:
                # 推广card
                $return = $this->h5_share_card($custom_type, $msg, $msg_source);
                return $return;
                break;

            case 66:
                # 系统消息
                $return = $this->h5_share_msg($custom_type, $msg, $msg_source);
                return $return;
                break;
        }
    }

    /* 帖子 */
    public function h5_share_release($custom_type, $msg, $msg_source)
    {
        $this->load->model('postm');
        $post_info = $this->postm->get_post_content((int)$msg, $cache = 1);
        if (empty($post_info)) return false;
        $custom_post = array();
        $custom_post['messageType'] = (string)substr($custom_type, 0, 1);
        $custom_post['msgContentId'] = (string)$msg;
        $custom_post['source'] = $msg_source;
        $custom_post['forwardUrl'] = $post_info['share_url'];
        if (in_array($post_info['post_type_extend'], array(4, 5))) {
            // 问答投票
            $custom_post['imageUrl'] = '';
            $custom_post['messageContent'] = $post_info['subject'];
        } else {
            // 病例
            $this->load->model('attachmentsm');
            $img_info = $this->attachmentsm->get_post_img_info((string)$msg);
            $custom_post['imageUrl'] = $img_info['img_list'][0];
            $custom_post['messageContent'] = $post_info['message'];
        }
        return $custom_post;
    }

    /* 专题 */
    public function h5_share_subject($custom_type, $msg, $msg_source)
    {
        $custom_post = array();
        $subject_info = $this->db->from("ml_disubject")->where(array("is_show" => 1, "id" => (int)$msg))->get()->result_array();
        if (empty($subject_info)) return false;
        $custom_post['messageType'] = (string)substr($custom_type, 0, 1);
        $custom_post['msgContentId'] = (string)$msg;
        $custom_post['source'] = $msg_source;
        $custom_post['forwardUrl'] = 'http://www.medical-lighter.com/disubject/show/' . (int)$msg;
        $custom_post['imageUrl'] = ret_fullpath_url($subject_info[0]['images_thumb']);
        $custom_post['messageContent'] = $subject_info[0]['title'];
        return $custom_post;
    }

    /* 推广card */
    public function h5_share_card($custom_type, $msg, $msg_source)
    {
        $custom_post = array();
        $ret = $this->db->select("title,content,addtime")->from("ml_apphelp")->where(array("is_show" => 1, "id" => (int)$msg))->get()->result_array();
        if (empty($ret)) return false;
        $custom_post['messageType'] = (string)substr($custom_type, 0, 1);
        $custom_post['msgContentId'] = (string)$msg;
        $custom_post['source'] = $msg_source;
        $custom_post['forwardUrl'] = 'http://www.medical-lighter.com/help/help_show/' . (int)$msg;
        $custom_post['imageUrl'] = 'http://static.medical-lighter.com/share/images/logo.jpg';
        $custom_post['messageContent'] = $ret[0]['title'];
        return $custom_post;
    }


    /* 系统消息 */
    public function  h5_share_msg($custom_type, $msg, $msg_source)
    {
        $custom_post = array();
        $ret = $this->db->select("title,content,addtime")->from("ml_apphelp")->where(array("is_show" => 1, "id" => (int)$msg))->get()->result_array();
        if (empty($ret)) return false;
        $custom_post['messageType'] = (string)substr($custom_type, 0, 1);
        $custom_post['msgContentId'] = (string)$msg;
        $custom_post['source'] = $msg_source;
        $custom_post['forwardUrl'] = 'http://www.medical-lighter.com/help/help_show/' . (int)$msg;
        $custom_post['imageUrl'] = 'http://static.medical-lighter.com/share/images/logo.jpg';
        $custom_post['messageContent'] = $ret[0]['title'];
        return $custom_post;
    }


    public function isRYOnline($uid)
    {
        $data = $this->rongyunim->userCheckOnline($uid);

        if ($data['code'] == 200 && $data['status'] == 1) {
            return true;
        }
        return false;
    }

    /**
     * 计算群聊管理员数目
     */
    public function gs_admin_count($gid)
    {
        if (!$gid) {
            return null;
        }
        $filter = array('gid'=>$gid,'mlv'=>self::MEMBER_LEVEL_SUB_ADMIN);
        $total  =  $this->db->where($filter)->from(self::TBL_NAME_GROUP_MEMBER)->count_all_results();
        return $total;

    }
    /**
     * 查询管理员和群主
     */
    public function get_admin_ids($gid)
    {
        if (!$gid) {
            return null;
        }
        $ids = $this->db->select('uid')->from(self::TBL_NAME_GROUP_MEMBER)->where('gid',$gid)->where_in('mlv',array(self::MEMBER_LEVEL_SUB_ADMIN,self::MEMBER_LEVEL_ADMIN))->get()->result_array();
        return array_column($ids,'uid');
    }

    /**
     * 申请是否已经被处理
     * @param $uid
     * @param $gid
     * @return array
     */
    public function is_expired_group($uid,$gid)
    {
        $res = $this->db->from(self::TBL_NAME_GROUP_APPLY_FOR)->where(array('gid'=>$gid,'from'=>$uid,'is_expired'=>0))->order_by('aid','desc')->get()->row_array();
        return $res;
    }

    /**
     * 返回群聊审核状态
     * @param $gid
     * @param $uid
     * @return int
     */
    public function get_apply_status($gid,$uid)
    {
        if(empty($gid)||empty($uid))
        {
            return 1;
        }else{
            $res = $this->db->select('apply_status')->from(self::TBL_NAME_GROUP_APPLY_FOR)->where(array('gid'=>$gid,'from'=>$uid))->order_by('aid','desc')->get()->row_array();
            if($res)
            {
                return $res['apply_status'];
            }else{
                return 1;
            }
        }
    } 
    /**
     * 删除推荐群缓存
     */
    public function delete_group_cache()
    {
        $key = self::MC_KEY_GROUP_RECOMMEND;
        $this->redis->delete($key);
    }


    public function queryInGroup($gid, $q, $page, $page_size=50)
    {
        $this->load->model('sphinxm');
        $sphinx = $this->sphinxm->getInstance(CORESEEK_IP_RYGROUP, CORESEEK_PORT_RYGROUP);
        $sphinx->SetRankingMode(SPH_RANK_PROXIMITY_BM25);
        $sphinx->SetLimits($page * $page_size, $page_size);

        $sphinx->SetFilter("gid", $gid);

        $sphinx->SetMatchMode(SPH_MATCH_ALL);
        $sphinx->SetGroupBy('uid', SPH_GROUPBY_ATTR);
        $res = $sphinx->Query($q, '*');


        $data = $res["matches"];

        $result = array();
        if (empty($data)) {
            return $result;
        }

        foreach ($data as $item) {
            if (empty($item["attrs"])) {
                continue;
            }

            $result[] = $item["attrs"];
        }

        return $result;
    }
}